import {messages} from "share/common";
/**
 *  created by zk on 2017/11/27
 */
import React from 'react'
import { connect } from 'react-redux'
import { Button, Form, Select,Input, Col, Row, Switch, message, Icon } from 'antd';
import cashService from 'containers/pay-setting/cash-transaction-class/cash-transaction-class-service';
import LanguageInput from 'components/template/language-input/language-input'
import httpFetch from 'share/httpFetch';
import config from 'config'
import menuRoute from 'routes/menuRoute'

import 'styles/pay-setting/cash-transaction-class/new-cash-transaction-class.scss'
const FormItem = Form.Item;
const Option = Select.Option;

class NewCashTransactionClass extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      loading: true,
      setOfBooks:[],
      typeCodes:[],
      mannerValue: null,
      cashTransactionClassDetail:menuRoute.getRouteItem('cash-transaction-class-detail', 'key'),
      cashTransactionClass:menuRoute.getRouteItem('cash-transaction-class', 'key'),
      writeOffList: [],
      i18n: []
    };
  }

  componentWillMount(){
    Promise.all([
      httpFetch.get(`${config.baseUrl}/api/setOfBooks/by/tenant?roleType=TENANT`),
      this.getSystemValueList(2104),
      cashService.getWriteOffList(this.props.company.setOfBooksId)
    ]).then(res => {
      this.setState({
        setOfBooks: res[0].data,
        typeCodes: res[1].data.values,
        writeOffList: res[2].data
      })
    }).catch(() => {
      message.error(messages('pay-setting.key62')/*系统异常*/);
    });
  }

  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  };

  //新建现金事务
  handleSave = (e) =>{
    e.preventDefault();
    const { i18n } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.prePaymentCode && (values.prePaymentCode = parseInt(values.prePaymentCode));
        values.isCompulsoryWriteOff && (values.isCompulsoryWriteOff = values.isCompulsoryWriteOff === '1');
        values.setOfBookId && values.setOfBookId === this.props.company.setOfBooksName && (values.setOfBookId = this.props.company.setOfBooksId);
        values.writeOffId && values.writeOffId.length > 0 && (values.writeOffId = values.writeOffId.join(','));
        values.i18n = {
          description: i18n
        };
        httpFetch.post(`${config.payUrl}/api/cash/transaction/classes`,values).then((response)=>{
          message.success(`${response.data.description}保存成功!`); /*保存成功！*/
          this.context.router.push(this.state.cashTransactionClassDetail.url.replace(':classId', response.data.id));
        }).catch((e)=>{
          this.setState({loading: false});
          if(e.response){
            message.error(`${messages("common.save.filed")},${e.response.data.message}`);
          }
        })
      }
    })
  };

  handleCancel = (e) =>{
    e.preventDefault();
    this.context.router.push(this.state.cashTransactionClass.url);
  };

  handlePeriodSetNameChange = (value, i18n) => {
    this.setState({ i18n });
  };

  render(){
    const { getFieldDecorator } = this.props.form;
    const { typeCodes, mannerValue, setOfBooks, writeOffList, i18n } = this.state;
    let zh_value = i18n.filter(item => item.language === "zh_cn").length > 0 ? i18n.filter(item => item.language === 'zh_cn')[0].value : undefined;
    return(
      <div className="new-cash-transaction-class">
        <div className="cash-transaction-class-form">
          <Form onSubmit={this.handleSave} className="cash-transaction-class-form">
            <Row gutter={60}>
              <Col span={8}>
                <FormItem
                  label={ messages('pay-setting.key1'/*账套*/) /*账套*/}
                  colon={true}>
                  {getFieldDecorator('setOfBookId', {
                    rules:[
                      {required:true,message: messages('common.please.select')},
                    ],
                    initialValue: this.props.company.setOfBooksName,
                  })(
                    <Select placeholder={ messages('common.please.select')} disabled={!this.props.tenantMode}>
                      {setOfBooks.map((option)=><Option key={option.id}>{option.setOfBooksName}</Option>)}
                    </Select>)
                  }
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem
                  label={ messages('pay-setting.key7'/*现金事务类型*/)} /*现金事务类型代码*/
                  colon={true}>
                  {getFieldDecorator('typeCode', {
                    rules:[
                      {required:true,message: messages('common.please.select')},
                    ]
                  })(
                    <Select onChange={(value)=>{this.setState({ mannerValue: value })}}
                            placeholder={ messages('common.please.select')}>
                      {typeCodes.map((option)=>{
                        return <Option key={option.value}>{option.messageKey}</Option>
                      })}
                    </Select>)
                  }
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem
                  label= { messages('pay-setting.key8'/*现金事务分类代码*/)}  /*现金事务分类代码*/
                  colon={true}>
                  {getFieldDecorator('classCode', {
                    rules:[
                      {required:true,message: messages('common.please.enter')},
                    ]
                  })(
                    <Input placeholder={ messages('common.please.enter')}/>)
                  }
                </FormItem>
              </Col>
            </Row>
            <Row gutter={60}>
              <Col span={8}>
                <FormItem label={messages('pay-setting.key9'/*现金事物分类名称*/)} colon={true}>
                  {getFieldDecorator('description', {
                    rules: [
                      {required: true, message: messages('common.please.enter')},
                    ]
                  })(
                    <LanguageInput
                      i18nName={i18n}
                      isEdit={i18n.length > 0 && i18n[0].value !== i18n[1].value}
                      value={zh_value}
                      nameChange={this.handlePeriodSetNameChange}
                    />
                  )}
                </FormItem>
              </Col>
              { mannerValue === 'PAYMENT' && (
                <Col span={8}>
                  <Col span={6}>
                    <FormItem label={messages('pay-setting.key75')/*核销对象*/} colon={true}>
                      {getFieldDecorator('writeOffType', {
                        rules: [{
                          required: true,
                          message: messages('common.please.select')
                        }],
                        initialValue: '1'
                      })(
                        <Select placeholder={messages('common.please.select')}
                                onChange={() => {
                                  this.props.form.setFieldsValue({writeOffId: undefined})
                                }}>
                          <Option key={'1'}>{messages('common.all')/*全部*/}</Option>
                          <Option key={'2'}>{messages('pay-setting.key76')/*部分*/}</Option>
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={16} offset={2}>
                    <FormItem style={{marginTop: '31px'}}>
                      {getFieldDecorator('writeOffId', {
                        rules: [{
                          message: messages('common.please.select'),
                          validator: (rule, value, cb) => {
                            if(this.props.form.getFieldValue('writeOffType') === '2'){
                              if(value.length === 0){
                                cb(false);
                              } else {
                                cb();
                              }
                            } else {
                              cb();
                            }
                          }
                        }]
                      })(
                        <Select placeholder={messages('common.please.select')}
                                disabled={this.props.form.getFieldValue('writeOffType') === '1'}
                                mode="multiple">
                          {writeOffList.map(item => {
                            return <Option key={item.id}>{item.description}</Option>
                          })}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                </Col>
              )}
              { mannerValue === "PREPAYMENT" &&
                <Col span={8}>
                  <FormItem label={messages('pay-setting.key68')/*预付款控制类型*/} colon={true}>
                    {getFieldDecorator('prePaymentCode', {
                      rules: [{
                        required: true,
                        message: messages('common.please.enter')
                      }]
                    })(
                      <Select placeholder={messages('common.please.select')}>
                        <Option key={1001}>{messages('pay-setting.key65')/*不控制*/}</Option>
                        <Option key={1002}>{messages('pay-setting.key66')/*同类型控制*/}</Option>
                        <Option key={1003}>{messages('pay-setting.key67')/*全控制*/}</Option>
                      </Select>)
                    }
                  </FormItem>
                </Col>
              }
              {
                mannerValue === 'PREPAYMENT' && <Col span={8}>
                  <FormItem label={messages('pay-setting.key72')/*强制核销控制类型*/}>
                    {getFieldDecorator('isCompulsoryWriteOff', {
                      rules: [
                        {required: true, message: messages('common.please.select')},
                      ]
                    })(
                      <Select  placeholder={messages('common.please.select')}>
                        <Option key={'1'}>{messages('pay-setting.key73')/*强制核销*/}</Option>
                        <Option key={'0'}>{messages('pay-setting.key74')/*不强制核销*/}</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
              }
              <Col span={8}>
                <FormItem label={messages('common.column.status')/* 状态 */}>
                  {getFieldDecorator('isEnabled', {
                    initialValue: true
                  })(
                    <Switch defaultChecked={true} checkedChildren={<Icon type="check"/>}
                            unCheckedChildren={<Icon type="cross"/>}/>
                  )}&nbsp;&nbsp;&nbsp;&nbsp;{this.props.form.getFieldValue('isEnabled') ? messages('common.status.enable') : messages('common.status.disable')}
                </FormItem>
              </Col>
            </Row>
            <Button type="primary" htmlType="submit">{messages('common.save') /*保存*/}</Button>
            <Button onClick={this.handleCancel} style={{ marginLeft: 8 }}> {messages('common.cancel') /*取消*/}</Button>
          </Form>
        </div>
      </div>
    )
  }
}

NewCashTransactionClass.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode
  }
}

const WrappedNewCashTransactionClass = Form.create()(NewCashTransactionClass);
export default connect(mapStateToProps)(WrappedNewCashTransactionClass);

